// 环境配置
const ENV = {
  development: 'http://localhost:8080/api',
  production: 'https://your-production-domain.com/api' // 这里替换为实际的生产环境域名
};

// 判断当前是否为开发环境
const isDev = () => {
  const accountInfo = wx.getAccountInfoSync();
  return accountInfo.miniProgram.envVersion === 'develop' || 
         accountInfo.miniProgram.envVersion === 'trial';
};

// 基础请求URL
const BASE_URL = isDev() ? ENV.development : ENV.production;

// 获取存储的token
const getToken = () => {
  return wx.getStorageSync('token') || '';
};

// 请求封装
const request = (options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${BASE_URL}${options.url}`,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': getToken(),
        ...options.header
      },
      success: (res) => {
        if (res.data.code === 200) {
          resolve(res.data.data);
        } else {
          wx.showToast({
            title: res.data.message || '请求失败',
            icon: 'none'
          });
          reject(res.data);
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        reject(err);
      }
    });
  });
};

// API接口
const API = {
  // 用户相关
  user: {
    login: (data) => request({
      url: '/user/login',
      method: 'POST',
      data
    }),
    register: (data) => request({
      url: '/user/register',
      method: 'POST',
      data
    }),
    getUserInfo: () => request({
      url: '/user/info'
    })
  },
  
  // 消息相关
  message: {
    list: () => request({
      url: '/message/list'
    }),
    publish: (data) => request({
      url: '/message/publish',
      method: 'POST',
      data
    }),
    reply: (data) => request({
      url: '/message/reply',
      method: 'POST',
      data
    })
  }
};

module.exports = {
  request,
  API,
  userApi: API.user  // 添加userApi导出
}; 